/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * 防抖
 * @author Farley
 * @date 2020-10-12
 * @param {function} fn   回调函数
 * @param {number} delay  时间
 * @returns {any}
 */
export function debounce(func, wait) {
  let timeout
  return function(...args) {
    const context = this // 保存当前上下文（Vue 实例）
    clearTimeout(timeout)
    timeout = setTimeout(() => func.call(context, ...args), wait) // 使用 call 方法来指定函数调用的上下文
  }
}

/**
 * 获取北京时间
 * @author Farley
 * @date 2020-10-12
 * @returns {object}  { 日期，时间 }
 */
export function getBJTime(time) {
  const add0 = num => (num < 10 ? '0' + num : num)
  let date, y, m, d, h, mm, s
  date = new Date(time)
  y = date.getFullYear()
  m = add0(date.getMonth() + 1)
  d = add0(date.getDate())
  h = add0(date.getHours())
  mm = add0(date.getMinutes())
  s = add0(date.getSeconds())
  return `${y}-${m}-${d} ${h}:${mm}:${s}`
}

/**
 * 获取北京时间
 * @author Farley
 * @date 2020-10-12
 * @returns {object}  { 日期，时间 }
 */
export function getBJTimes() {
  const add0 = num => (num < 10 ? '0' + num : num)
  let date, y, m, d, h, mm, s
  date = new Date()
  y = date.getFullYear()
  m = add0(date.getMonth() + 1)
  d = add0(date.getDate())
  h = add0(date.getHours())
  mm = add0(date.getMinutes())
  s = add0(date.getSeconds())
  return `${h}:${mm}:${s}`
}
/**
 * 获取北京日期
 * @author Farley
 * @date 2020-10-12
 * @returns {object}  { 日期，时间 }
 */
export function getBJDate() {
  const add0 = num => (num < 10 ? '0' + num : num)
  let date, y, m, d, h, mm, s
  date = new Date()
  y = date.getFullYear()
  m = add0(date.getMonth() + 1)
  d = add0(date.getDate())
  h = add0(date.getHours())
  mm = add0(date.getMinutes())
  s = add0(date.getSeconds())
  return `${m}-${d}`
}

// 定义一个函数来转换null为0
export function convertNullsToZeros(arr) {
  return arr.map(obj => {
    // 使用Object.keys()获取对象的所有键，然后遍历它们
    Object.keys(obj).forEach(key => {
      // 检查当前属性的值是否为null
      if (obj[key] === null) {
        // 如果是，则将其设置为0
        obj[key] = 0
      }
    })
    // 返回修改后的对象
    return obj
  })
}
function isEmpty(value) {
  // 判断一个值是否为空
  return (
    value === null ||
    value === undefined ||
    value === '' ||
    Number.isNaN(value) ||
    (Array.isArray(value) && value.length === 0) ||
    (typeof value === 'object' && Object.keys(value).length === 0)
  )
}
export function areAllFieldsEmpty(obj) {
  // 检查对象（及其嵌套对象/数组）的所有字段是否都为空
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key]
      if (!isEmpty(value)) {
        // 如果当前字段不为空，则返回false
        return false
      }
      if (typeof value === 'object' && value !== null) {
        // 如果字段是对象或数组，递归检查
        if (!areAllFieldsEmpty(value)) {
          return false
        }
      }
    }
  }
  // 所有字段都检查完毕，且都为空
  return true
}
// 计算结束时间是否小于开始时间
export function compareDates(startDateStr, endDateStr) {
  const startDate = new Date(startDateStr).getTime()
  const endDate = new Date(endDateStr).getTime()
  return endDate >= startDate // 如果结束时间不小于开始时间，则返回true
}
// 把不带双引号的label改为带双引号的label
export const handleLabel = valueStr => {
  let toLabel = valueStr.replace(/(?<!")\blabel\b(?=: )/g, '"label"')
  toLabel = JSON.stringify(toLabel)

  let toJSON = JSON.parse(toLabel)
  toJSON = toJSON.replace(/(?<!")\blabel\b(?=: )/g, 'label')
  return Array.from(JSON.parse(toJSON))
}
